/**
 * HTML到Markdown转换工具
 * 支持语雀、知乎等平台的HTML内容转换
 */

export interface ConversionOptions {
  preserveImages?: boolean;
  preserveLinks?: boolean;
  preserveTables?: boolean;
  preserveCodeBlocks?: boolean;
}

/**
 * HTML到Markdown转换器
 */
export class HtmlToMarkdownConverter {
  private options: ConversionOptions;

  constructor(options: ConversionOptions = {}) {
    this.options = {
      preserveImages: true,
      preserveLinks: true,
      preserveTables: true,
      preserveCodeBlocks: true,
      ...options
    };
  }

  /**
   * 转换HTML为Markdown
   */
  convert(html: string): string {
    // 创建临时DOM元素
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = html;
    
    // 递归处理节点
    const markdown = Array.from(tempDiv.childNodes)
      .map(node => this.processNode(node))
      .join('');
    
    // 清理多余的空白行
    return this.cleanupMarkdown(markdown);
  }

  /**
   * 处理单个节点
   */
  private processNode(node: Node): string {
    if (node.nodeType === Node.TEXT_NODE) {
      return node.textContent || '';
    }
    
    if (node.nodeType === Node.ELEMENT_NODE) {
      const element = node as Element;
      const tagName = element.tagName.toLowerCase();
      const children = Array.from(element.childNodes)
        .map(child => this.processNode(child))
        .join('');
      
      return this.processElement(tagName, element, children);
    }
    
    return '';
  }

  /**
   * 处理HTML元素
   */
  private processElement(tagName: string, element: Element, children: string): string {
    switch (tagName) {
      // 标题
      case 'h1': return `# ${children}\n\n`;
      case 'h2': return `## ${children}\n\n`;
      case 'h3': return `### ${children}\n\n`;
      case 'h4': return `#### ${children}\n\n`;
      case 'h5': return `##### ${children}\n\n`;
      case 'h6': return `###### ${children}\n\n`;
      
      // 段落和换行
      case 'p': return `${children}\n\n`;
      case 'br': return '\n';
      case 'hr': return '---\n\n';
      
      // 文本格式
      case 'strong':
      case 'b': return `**${children}**`;
      case 'em':
      case 'i': return `*${children}*`;
      case 'del':
      case 's': return `~~${children}~~`;
      case 'code': return `\`${children}\``;
      
      // 代码块
      case 'pre': {
        if (this.options.preserveCodeBlocks) {
          const content = element.textContent || '';
          const language = this.detectCodeLanguage(element);
          return `\`\`\`${language}\n${content}\n\`\`\`\n\n`;
        }
        return `${children}\n\n`;
      }
      
      // 链接
      case 'a': {
        if (this.options.preserveLinks) {
          const href = element.getAttribute('href') || '';
          const title = element.getAttribute('title') || '';
          const linkText = title ? `[${children}](${href} "${title}")` : `[${children}](${href})`;
          return linkText;
        }
        return children;
      }
      
      // 图片
      case 'img': {
        if (this.options.preserveImages) {
          const src = element.getAttribute('src') || '';
          const alt = element.getAttribute('alt') || '';
          const title = element.getAttribute('title') || '';
          const imgText = title ? `![${alt}](${src} "${title}")` : `![${alt}](${src})`;
          return imgText;
        }
        return '';
      }
      
      // 引用
      case 'blockquote': return `> ${children}\n\n`;
      
      // 列表
      case 'ul': {
        const items = element.querySelectorAll('li');
        return Array.from(items)
          .map(item => `- ${item.textContent?.trim() || ''}`)
          .join('\n') + '\n\n';
      }
      
      case 'ol': {
        const items = element.querySelectorAll('li');
        return Array.from(items)
          .map((item, index) => `${index + 1}. ${item.textContent?.trim() || ''}`)
          .join('\n') + '\n\n';
      }
      
      // 表格
      case 'table': {
        if (this.options.preserveTables) {
          return this.processTable(element);
        }
        return children;
      }
      
      // 语雀特有元素
      case 'div': {
        // 处理语雀的代码块容器
        if (element.classList.contains('lake-code') || element.classList.contains('code-block')) {
          const codeElement = element.querySelector('pre, code');
          if (codeElement) {
            const content = codeElement.textContent || '';
            const language = this.detectCodeLanguage(codeElement);
            return `\`\`\`${language}\n${content}\n\`\`\`\n\n`;
          }
        }
        
        // 处理语雀的图片容器
        if (element.classList.contains('lake-image') || element.classList.contains('image-block')) {
          const imgElement = element.querySelector('img');
          if (imgElement) {
            return this.processElement('img', imgElement, '');
          }
        }
        
        return children;
      }
      
      // 其他元素
      default: return children;
    }
  }

  /**
   * 处理表格
   */
  private processTable(tableElement: Element): string {
    const rows = tableElement.querySelectorAll('tr');
    let tableMarkdown = '';
    
    rows.forEach((row, rowIndex) => {
      const cells = row.querySelectorAll('td, th');
      const rowMarkdown = '| ' + Array.from(cells)
        .map(cell => cell.textContent?.trim() || '')
        .join(' | ') + ' |';
      
      tableMarkdown += rowMarkdown + '\n';
      
      // 添加表头分隔符
      if (rowIndex === 0) {
        const separator = '| ' + Array.from(cells)
          .map(() => '---')
          .join(' | ') + ' |';
        tableMarkdown += separator + '\n';
      }
    });
    
    return tableMarkdown + '\n';
  }

  /**
   * 检测代码语言
   */
  private detectCodeLanguage(element: Element): string {
    // 检查class中的语言标识
    const classList = element.className;
    const languageMatch = classList.match(/language-(\w+)/);
    if (languageMatch) {
      return languageMatch[1];
    }
    
    // 检查data属性
    const dataLang = element.getAttribute('data-lang');
    if (dataLang) {
      return dataLang;
    }
    
    // 检查语雀特有的语言标识
    const yuqueLang = element.getAttribute('data-lang');
    if (yuqueLang) {
      return yuqueLang;
    }
    
    return '';
  }

  /**
   * 清理Markdown内容
   */
  private cleanupMarkdown(markdown: string): string {
    return markdown
      // 清理多余的空白行
      .replace(/\n\s*\n\s*\n/g, '\n\n')
      // 清理行首行尾空白
      .trim();
  }

  /**
   * 检测是否为语雀内容
   */
  static isYuqueContent(html: string): boolean {
    return html.includes('lake-') || html.includes('yuque') || html.includes('语雀');
  }

  /**
   * 检测是否为知乎内容
   */
  static isZhihuContent(html: string): boolean {
    return html.includes('ztext') || html.includes('知乎') || html.includes('zhihu');
  }

  /**
   * 检测内容来源
   */
  static detectSource(html: string): string {
    if (this.isYuqueContent(html)) return 'yuque';
    if (this.isZhihuContent(html)) return 'zhihu';
    return 'unknown';
  }
}

/**
 * 便捷的转换函数
 */
export const htmlToMarkdown = (html: string, options?: ConversionOptions): string => {
  const converter = new HtmlToMarkdownConverter(options);
  return converter.convert(html);
};
